package com.project.demo.api;

import com.project.demo.model.User;
import com.project.demo.model.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Time:23:10
 */
@RestController
public class UserAPI {
    @Resource
    private UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password,HttpServletRequest request){
        //根据username在数据库中查询，如果能找到匹配的用户，密码也一致，则登录成功
        User user = userMapper.selectByName(username);
        System.out.println("[login] username=" + username);
        if (user==null||!user.getPassword().equals(password)){
            //登录失败
            System.out.println("登录失败！");
            return new User();
        }
        HttpSession session = request.getSession(true);//会话存在，则直接返回，不存在则创建一个会话
        session.setAttribute("user",user);
        return user;
    }

    @PostMapping("/register")
    @ResponseBody
    public Object register(String username,String password){
        try {
            User user=new User();
            user.setUsername(username);
            user.setPassword(password);
            userMapper.insert(user);
            return user;
        }catch (org.springframework.dao.DuplicateKeyException e){
            User user =new User();
            return user;
        }
    }

    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest request){
        try {
            HttpSession session = request.getSession(false);//会话存在，则直接返回，不存在，则返回空
            User user = (User) session.getAttribute("user");
            return user;
        }catch (NullPointerException e){
            return new User();
        }

    }
}
